home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Extensions / Imaging / Scripts / painter.py < prev    next >
Encoding:
Python Source  |  2000-06-23  |  1.7 KB  |  73 lines

  1. #
  2. # The Python Imaging Library
  3. # $Id: painter.py,v 1.1.1.1 1998/08/18 13:07:58 sjoerd Exp $
  4. #
  5. # this demo script illustrates pasting into an already displayed
  6. # photoimage.  note that the current version of Tk updates the whole
  7. # image everytime we paste, so to get decent performance, we split
  8. # the image into a set of tiles.
  9. #
  10.  
  11. from Tkinter import *
  12. import Image, ImageTk
  13. import sys
  14.  
  15. #
  16. # painter widget
  17.  
  18. class PaintCanvas(Canvas):
  19.     def __init__(self, master, image):
  20.     Canvas.__init__(self, master, width=image.size[0], height=image.size[1])
  21.  
  22.     # fill the canvas
  23.     self.tile = {}
  24.     self.tilesize = tilesize = 32
  25.     xsize, ysize = image.size
  26.     for x in range(0, xsize, tilesize):
  27.         for y in range(0, ysize, tilesize):
  28.         box = x, y, min(xsize, x+tilesize), min(ysize, y+tilesize)
  29.         tile = ImageTk.PhotoImage(image.crop(box))
  30.         self.create_image(x, y, image=tile, anchor=NW)
  31.         self.tile[(x,y)] = box, tile
  32.  
  33.     self.image = image
  34.  
  35.     self.bind("<B1-Motion>", self.paint)
  36.  
  37.     def paint(self, event):
  38.     xy = event.x - 10, event.y - 10, event.x + 10, event.y + 10
  39.     im = self.image.crop(xy)
  40.  
  41.     # process the image in some fashion
  42.         im = im.convert("L")
  43.  
  44.     self.image.paste(im, xy)
  45.     self.repair(xy)
  46.  
  47.     def repair(self, box):
  48.     # update canvas
  49.     dx = box[0] % self.tilesize
  50.     dy = box[1] % self.tilesize
  51.     for x in range(box[0]-dx, box[2]+1, self.tilesize):
  52.         for y in range(box[1]-dy, box[3]+1, self.tilesize):
  53.         try:
  54.             xy, tile = self.tile[(x, y)]
  55.             tile.paste(self.image.crop(xy))
  56.         except KeyError:
  57.             pass # outside the image
  58.     self.update_idletasks()
  59.  
  60. #
  61. # main
  62.  
  63. root = Tk()
  64.  
  65. im = Image.open(sys.argv[1])
  66.  
  67. if im.mode != "RGB":
  68.     im = im.convert("RGB")
  69.  
  70. PaintCanvas(root, im).pack()
  71.  
  72. root.mainloop()
  73.